package uf.audit.demo.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

import uf.audit.demo.biz.UFBiz;
import uf.audit.tax.platform.core.authority.AuthFilter;
import uf.audit.tax.platform.core.authority.AuthMgr;
import uf.audit.tax.platform.core.spring.bean.ILogInfo;
import uf.audit.tax.platform.core.spring.bean.IUser;
import uf.audit.tax.platform.util.Consts;
import uf.audit.tax.platform.util.JSONUtil;
import uf.audit.tax.platform.util.Utils;
import uf.audit.tax.platform.util.sso.UserInfo;
import uf.audit.tax.platform.web.UFBaseController;

/**
 * SSO登录/登出模式
 * 
 * @author sunny
 *
 */

public class StandardLogin implements ILogInfo {

	IUser user;

	public IUser getUser() {
		return user;
	}

	public void setUser(IUser user) {
		this.user = user;
	}

	/**
	 * 防止爆破，增加逻辑 用户名或密码输入错误5次了，系统自动禁用用户，让系统管理员给解开
	 * 逻辑修改为：先查用户名密码输入对不对（如果不对错误次数+1），再查是否可用
	 */
	@Override
	public Boolean login(Controller con) {
		UFBaseController bcon = (UFBaseController) con;
		HttpServletRequest req = bcon.getRequest();
		if (req.getMethod().equalsIgnoreCase("get")) {
			if (Utils.isLogin(bcon)) {
				bcon.redirect("/sys/index");
			} else {
				bcon.render("login.html");
			}
		} else {
			// POST登录方法仅仅在服务端支持
			JSONObject info = JSONUtil.parseObject(bcon.getPostData());
			String name = info.getString("name");
			String password = info.getString("password");
			String user_id = user.checkeUser(name, password);
			if (!user_id.equals("0")) {
				if (user.isEnabled(user_id)) {
					Utils.setLogin(bcon, name, user_id);
					user.updateUserToken(bcon);
					UserInfo userInfo = UFBiz.buildUserInfo(user_id);
					Utils.saveUserInfo(req, bcon.getResponse(), userInfo);
					userInfo = Utils.getUserInfo(req);
					UFBiz.saveUserInfo(bcon, userInfo);
//					user.updateCwcs(name, 0, false); // 登录成功，错误次数置0
					bcon.renderJson("{\"status\": \"ok\"}");
				} else {
					bcon.renderJson("{\"status\": \"此用户已被禁用，请联系系统管理员\"}");
				}
			} else {
//				user.updateCwcs(name); // 登录失败，错误次数加一
				bcon.renderJson("{\"status\": \"error\"}");
			}
		}
		return true;
	}

	@Override
	public Boolean logout(Controller con) {
		Utils.setLogout(con);
		Utils.cleanLogin(con.getRequest(), con.getResponse());
		con.redirect("/pub/login");
		return true;
	}

	@Override
	public void intercept(Invocation inv, Interceptor caller) {
		Controller con = inv.getController();
		HttpServletRequest req = con.getRequest();
		UserInfo userInfo = Utils.getUserInfo(req);
		if (userInfo == null) {
			con.redirect("/pub/index");
			return;
		}
		Utils.setLogin(con, userInfo.getUserName(), userInfo.getUserBh());
		AuthFilter.loginAfter(req);
		boolean lookup = AuthFilter.lookup(req);
		String userName = Utils.getUserName(con);
		if (userName.equals(Consts.ADMIN_USER)) {
			inv.invoke();
			return;
		}
		List<String> tokens = AuthMgr.buildAuthToken(inv);
		String userId = Utils.getUserId(con);
		try {
			if (tokens != null && !tokens.isEmpty()) {
				boolean passed = false;
				for (String token : tokens) {
					if (AuthMgr.checkAuth(token, userId)) {
						passed = true;
						break;
					}
				}
				if (!passed) {
					inv.getController().renderError(403);
					return;
				}
			}
			if (!lookup) {
				AuthFilter.loginAfter(req);
				lookup = AuthFilter.lookup(con.getRequest());
			}
			inv.invoke();
		} finally {

		}
	}
}
